﻿var easyUI = {
	fpbind:function(){
		if(!Function.prototype.bind){
			Function.prototype.bind = function(obj){
				var owner = this,args = Array.prototype.slice.call(arguments),callobj = Array.prototype.shift.call(args);
				return function(e){e=e||top.window.event||window.event;owner.apply(callobj,args.concat([e]));};
			};
		}
	}(),
	IAHTML:function(){
		if(document.body.insertAdjacentHTML){return;}
		HTMLElement.prototype.insertAdjacentHTML = function(sWhere, sHTML){
			var df = null,r = this.ownerDocument.createRange();
			switch (String(sWhere).toLowerCase()) {
				case "beforebegin":
					r.setStartBefore(this);
					df = r.createContextualFragment(sHTML);
					this.parentNode.insertBefore(df, this);
					break;
				case "afterbegin":
					r.selectNodeContents(this);
					r.collapse(true);
					df = r.createContextualFragment(sHTML);
					this.insertBefore(df, this.firstChild);
					break;
				case "beforeend":
					r.selectNodeContents(this);
					r.collapse(false);
					df = r.createContextualFragment(sHTML);
					this.appendChild(df);
					break;
				case "afterend":
					r.setStartAfter(this);
					df = r.createContextualFragment(sHTML);
					this.parentNode.insertBefore(df, this.nextSibling);
					break;
			}
		};
	}(),
	getPosition:function(){
		return document.documentElement.getBoundingClientRect && function(o){//IE,FF,Opera
			var pos = o.getBoundingClientRect(), root = o.ownerDocument || o.document;
			return {x:pos.left+root.documentElement.scrollLeft,y:pos.top+root.documentElement.scrollTop};
		} || function(o){//Safari,Chrome,Netscape,Mozilla
			var x = 0, y = 0;
			do{x += o.offsetLeft;y += o.offsetTop;}while((o=o.offsetParent));
			return {'x':x,'y':y};
		};
	}(),
	setPosition:function(obj,x,y){
		obj.style.left = x + "px";
		obj.style.top = y + "px";
	},
	getStyle:function(dom,stylename){
		if(dom.currentStyle){
			return dom.currentStyle[stylename];
		}else{
			return window.getComputedStyle(dom,null).getPropertyValue(stylename);
		}
	},
	stopEvent:function(e){
		e = e||window.event;
		if(e.stopPropagation){e.stopPropagation();}else{e.cancelBubble = true;}
		if(e.preventDefault){e.preventDefault();}else{e.returnValue = false;}
	},
	ajax:{
		tryList:function(){
			var xhr = null;
			for(var i=0;i<arguments.length;i++){
				var lambda = arguments[i];
				try{xhr = lambda();break;}catch(e){}
			}
			return xhr;
		},
		init:function(){
			return this.tryList(
				function(){return new ActiveXObject('MSXML2.XMLHttp.6.0');},
				function(){return new ActiveXObject('MSXML2.XMLHttp.3.0');},
				function(){return new XMLHttpRequest();},
				function(){return new ActiveXObject('MSXML2.XMLHttp.5.0');},
				function(){return new ActiveXObject('MSXML2.XMLHttp.4.0');},
				function(){return new ActiveXObject('Msxml2.XMLHTTP');},
				function(){return new ActiveXObject('MSXML.XMLHttp');},
				function(){return new ActiveXObject('Microsoft.XMLHTTP');}
				) || null;
		},
		post:function(sUrl,sArgs,bAsync,fCallBack,errmsg){
			var xhr = this.init();
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4){
					if(xhr.responseText){
						if(fCallBack.constructor==Function){fCallBack(xhr);}
					}else{
						alert(errmsg);
					}
				}
			};
			xhr.open('POST',encodeURI(sUrl),bAsync);
			xhr.setRequestHeader('Content-Length',sArgs.length);
			xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			xhr.send(sArgs);
		},
		get:function(sUrl,bAsync,fCallBack,errmsg){
			var xhr = this.init();
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4){
					if(xhr.responseText){
						if(fCallBack.constructor==Function){fCallBack(xhr);}
					}else{
						alert(errmsg);
					}
				}
			};
			xhr.open('GET',encodeURI(sUrl),bAsync);
			xhr.send('Null');
		}
	},
	clearTxtNode:function(Elm){
		if(!Elm){return;}
		var dchild = Elm.childNodes;
		for(var i=0;i<dchild.length;i++){
			if(dchild[i].nodeType==3&&!dchild[i].nodeValue.replace(/\s/g,'').length){Elm.removeChild(dchild[i]);}
		}
	}
};

var Dhatv = function(dbox,root,maxlength){
	this.ajaxerror = '服务器错误，请稍候重试或与管理员联系！';
	this.checkbox = false;//复选框
	this.constructor = arguments.callee;
	this.datasource = [];
	this.dataurl = '';
	this.editurl = '';
	this.editable = false;
	this.editmenu = null;
        this.editMenuContents = [];
        this.editMenuFunction = [];
	this.editpanel = null;
	this.extpp = [];
	this.iconpath = 'folder/';
	this.maxlength = maxlength||100;
	this.onNodeClick = function(node){alert('onNodeClick:\n'+node);};
	this.onNodeDblClick = function(node){alert('onNodeDblClick:\n'+node);};
	this.onContextMenu = function(node){alert('onContextMenu:\n'+node);};
	this.onNodeOpen = function(node){alert('onNodeOpen:\n'+node);};
	this.onNodeFocus = function(node){alert('onNodeFocus:\n'+node);};
	this.onNodeChecked = function(node){alert('onNodeChecked:\n'+node);};
	this.onNodeUnChecked = function(node){alert('onNodeUnChecked:\n'+node);};
	this.root = root||'dhATV V4.0';
        this.rootEditable = false;
	this.sortable = false;
	this.sortIndex = 0;
	this.selectedNode = null;
	this.treebox = dbox;
};
Dhatv.prototype = {
	clearNode:function(node){//清除节点
		var dparent = node.parentNode,dpparent = node.parentNode.parentNode;
		var datasource = this.datasource;
		dparent.removeChild(node);
		var dchild = null,dimg = null,i=0;
		if(!dparent.childNodes.length){
			this.folder2TxtNode(dpparent);//目录节点转变为文本节点
		}else{
			this.resetLastChild(dpparent);//最后一个节点改变样式
		}
	},
	checkUp:function(node){//向上设置checkbox
		try{
			var chkall = true;
			var chkbox = node.parentNode.getElementsByTagName("Input");
			for(var n=0;n<chkbox.length;n++){
				if(!chkbox[n].checked){
					chkall=false;
					break;
				}
			}
			var nodeParent = node.parentNode.parentNode,checkstate = nodeParent.childNodes[2].checked;
			nodeParent.childNodes[2].checked = chkall?true:false;
			if(chkall&&!checkstate&&this.onNodeChecked&&this.onNodeChecked.constructor==Function){this.onNodeChecked(nodeParent);}//选中事件
			if(!chkall&&checkstate&&this.onNodeUnChecked&&this.onNodeUnChecked.constructor==Function){this.onNodeUnChecked(nodeParent);}//取消选中事件
			this.checkUp(nodeParent);
		}catch(e){}
	},
	editEvent:function(e){//编辑菜单事件
		var dtarg = e.srcElement||e.target;
		easyUI.stopEvent(e);
		this.hideEditMenu();
                if (this.editMenuContents.length < 1) {
                    return;
                }
		if(dtarg.tagName=='A'){
                    var commandText = dtarg.innerHTML;
                    for (var i = 0;i < this.editMenuContents.length; i++) {
                        if (commandText == this.editMenuContents[i] && this.editMenuFunction[i] && this.editMenuFunction[i].constructor == Function) {
                            this.editMenuFunction[i](this.selectedNode);
                        }
                    }
		}
	},
	expandNode:function(node){//展开指定的节点
		if(!node){return;}
		this.openUp(node);
		this.setFocus(node);
		this.openNode(node);
	},
	focusNode:function(aIndex,callback){//设置焦点到指定位置的节点[0,0,0] 0->0->0
		if(!aIndex||aIndex.constructor!=Array){return;}
		var root = this.treebox.firstChild.firstChild;//根节点
		if(!root){return;}
		if(aIndex.length<2){//设置根目录获得焦点
			this.setFocus(root);
			if(callback&&callback.constructor==Function){callback();}
			return;
		}
		var maxlength = this.maxlength;
		aIndex[0] = 0;//强制起始位置为根节点
		var tmpNode = root,lastNode = null;
		var searchEx = function(){//搜索已存在节点
			if(tmpNode&&tmpNode.lastChild.childNodes.length){aIndex.shift();}
			var i = -1;
			while(aIndex.length&&tmpNode&&tmpNode.lastChild.childNodes.length){
				lastNode = tmpNode;i = aIndex.shift();
				tmpNode = tmpNode.lastChild.childNodes[i]||null;
			}
			tmpNode = (tmpNode)?tmpNode:lastNode;//返回最后有效节点
			if(i>=0&&aIndex.length){aIndex.unshift(i);}//当有处理子节点并且索引序列尚未结束时，重新插入该节点索引
		};
		var searchAsync = function(childNodes,node,aSearch){//异步搜索
			if(aSearch.length===0){//当遍历完索引仍然没有找到，聚焦到当前节点
				this.openUp(node);
				this.setFocus(node);
				childNodes=node=null;return;
			}
			var depart = aSearch&&aSearch.shift();
			if(depart<0||isNaN(depart)){depart = 0;}
			if(childNodes&&childNodes.length>0){
				this.insertNode(childNodes,node);
				var dli = node.getElementsByTagName('li');
				if(depart>=childNodes.length){//当索引值超过子节点数，聚焦到当前节点
					this.openUp(node);
					this.setFocus(node);
					childNodes=node=null;return;
				}
				if(aSearch.length===0){
					var dIndex = dli[depart];
					this.openUp(dIndex);
					this.setFocus(dIndex);
					if(callback&&callback.constructor==Function){callback();}
					childNodes=node=null;
					return;
				}
				node = dli[depart];
			}
			var atid = node.getAttribute('atid');
			var pid = node.getAttribute('pid');
			this.getData(atid,pid,0,arguments.callee,[node,aSearch,maxlength]);//异步哦 ^_^
		};
		searchEx();
		searchAsync.call(this,null,tmpNode,aIndex.slice(0));
		root = tmpNode = lastNode = null;
	},
	folder2TxtNode:function(node){//目录节点转变为文本节点
		if(!node){return;}
		var dul = node.lastChild;
		if(dul){
			dul.style.display = 'none';
			dul.innerHTML = '';
		}
		node.className = node.className.replace(/folder/i,'text');
		var dchild = node.childNodes,dimg = null;
		for(var i=0;i<dchild.length;i++){
			dimg = dchild[i];
			if(dimg.tagName=='IMG'){
				dimg.className = dimg.className.replace(/f(l?)\-open/i,'t$1');
			}
		}
	},
	getData:function(atid,pid,more,callback,args){//返回指定节点子数据
		if(this.datasource.constructor==Array&&this.datasource.length>0){return this.getDataSource(atid,pid,more,callback,args);}
		if(this.dataurl.replace(/\s/g,'').length>0){return this.getDataUrl(atid,pid,more,callback,args);}
	},
	getDataSource:function(atid,pid,more,callback,args){//取静态数据
		var data = this.datasource,il = data.length,arv = [],rlen = (parseInt(this.maxlength,10)+1);
		for(var i=0;i<il;i++){
			if(arv.length>=rlen){break;}
			if(more){
				if(data[i][0]>atid&&data[i][1]==pid){//查询atid比atid大，并且pid等于pid的数据，长度达到指定长度即返回，同样适用于服务端查询
					arv.push(data[i]);
				}
			}else{
				if(data[i][1]==atid){
					arv.push(data[i]);
				}
			}
		}
		if(callback&&callback.constructor==Function){callback.apply(this,[arv.slice(0)].concat(args));}
		return arv.slice(0);
	},
	getDataUrl:function(atid,pid,more,callback,args){//取服务端数据
		var surl = this.dataurl,sarg = 'atid='+atid+'&pid='+pid+'&more='+more+'&l='+(parseInt(this.maxlength,10)+1);
		var tv = this;
                if (surl.indexOf('?') > 0) {
                    var targs =  surl.substring(surl.indexOf('?') + 1).replace('atid=', '1=');
                    surl = surl.substring(0,surl.indexOf('?'));
                }
		var xrcb = function(xhr){
			if(xhr){
				var rpt = unescape(xhr.responseText);
				var rv = null;
				if(rpt.replace(/\s/g,'')!==''){
					rv = eval('0,'+rpt);
					if(callback&&callback.constructor==Function){callback.apply(tv,[rv].concat(args));}
				}
				return rv;
			}
			return null;
		};
		easyUI.ajax.post(surl,sarg+'&'+targs,true,xrcb,this.ajaxerror);
	},
	getNodeList:function(node){//取节点索引序列
		if(!node){return null;}
		var list = [];
		do{
			if(!node||node.tagName!='LI'){break;}
			var i = 0;
			do{
				if(!node.previousSibling||node.previousSibling.tagName!='LI'){break;}
				i++;node = node.previousSibling;
			}while(node);
			list.push(i);
		}while(node.parentNode&&(node=node.parentNode.parentNode));
		return list.reverse().slice(0);
	},
	hideEditMenu:function(){//关闭编辑菜单
		this.editmenu.style.visibility = 'hidden';
	},
	insertNode:function(childNodes,node){//插入节点[[autoID,parentID,nodeValue,hasChildNodes],...]
		if(node&&childNodes&&childNodes.constructor==Array&&childNodes.length>0){
			var dul = node.lastChild;//ul
			var dlast = dul&&dul.lastChild;//node下ul元素中最后一个li
			var mcnl = childNodes.length;
			if(mcnl>this.maxlength){--childNodes.length;}
			//alert(dul+'\n'+dlast+'\n'+node);
			var chkbox = node&&node.childNodes[2];
			var checked = (chkbox&&chkbox.tagName=='INPUT')?chkbox.checked:false;//是否选中
			var chkStr = (this.checkbox)?(checked)?'<input type="checkbox" checked="checked" />':'<input type="checkbox" />':'';//复选框
			//将倒三角去掉即可
                        var editStr = '';//(this.editable)?'<img class="tvedit" src="'+this.iconpath+'space.gif" />':'';
			var aCNS = [],cnl = childNodes.length,A,P,T,S,tmpCN,cnfl,epn,extpp,sortable = this.sortable,si = this.sortIndex;
			if(sortable){//排序
				childNodes.sort(function(a,b){
					var x = a[si]||0,y = b[si]||0;
					return !isNaN(x)?(sortable.toString().toLowerCase()=='desc')?y-x:x-y:(sortable.toString().toLowerCase()=='desc')?y.localeCompare(x):x.localeCompare(y);
				});
			}
			for(var i=0;i<cnl;i++){
				tmpCN = childNodes[i];cnfl = tmpCN.length;epn='';extpp = '';
				A = tmpCN[0];P = tmpCN[1];T = tmpCN[2];S = tmpCN[3];//必须属性atid,pid,nodevalue,haschild
				if(cnfl>4){//扩展属性，自动冠名为 extpp1,extpp2......
					for(var n=4;n<cnfl;n++){
						epn = (this.extpp.length&&this.extpp[n-4])?this.extpp[n-4]:'extpp'+(n-3);
						extpp += ' '+epn+'="'+tmpCN[n]+'"';
					}
				}
				if(S){//目录节点
					aCNS[i] = '<li class="folder" atid="'+A+'" pid="'+P+'" txt="'+T+'"'+extpp+'><img class="tvdash-f" src="'+this.iconpath+'space.gif" /><img class="tvicon-f" src="'+this.iconpath+'space.gif" />'+chkStr+editStr+'<a href="#">'+T+'</a><ul></ul></li>';
				}else{//文本节点
					aCNS[i] = '<li class="text" atid="'+A+'" pid="'+P+'" txt="'+T+'"'+extpp+'><img class="tvdash-t" src="'+this.iconpath+'space.gif" /><img class="tvicon-t" src="'+this.iconpath+'space.gif" />'+chkStr+editStr+'<a href="#">'+T+'</a><ul></ul></li>';
				}
			}
			if(mcnl>this.maxlength){//添加继续加载剩余数据节点
				aCNS.push('<li class="textl" atid="'+A+'" pid="'+P+'" txt="getmore"><img class="tvdash-tl" src="'+this.iconpath+'space.gif" /><img class="tvicon-tl" src="'+this.iconpath+'space.gif" /><a href="#">点击继续加载...</a></li>');
			}else{//全部数据已加载结束，将最后一个节点设置为树梢 ^_^
				var stmp = aCNS[aCNS.length-1];
				//prompt('x',stmp);
				stmp = stmp.replace(/class="(folder|text|tvdash-f|tvdash-t|tvicon-f|tvicon-t)"/ig,'class="$1l"');
				aCNS[aCNS.length-1] = stmp;
			}
			if(dlast&&dlast.getAttribute('txt')=='getmore'){dul.removeChild(dlast);}//移除点击继续加载的节点
			dul.insertAdjacentHTML('beforeend',aCNS.join(''));//插入新节点
		}
	},
	openNode:function(node,dtarg){//展开节点
		var atid = node&&node.getAttribute('atid');
		var pid = node&&node.getAttribute('pid');
		var txt = node&&node.getAttribute('txt');
		var cls = node&&node.className;
		var more = (txt=='getmore');
		if(more&&dtarg){//点击的目标是加载更多
			dtarg.innerHTML = '<img src="'+this.iconpath+'indicator_arrow.gif" /> 正在加载数据...';
			this.getData(atid,pid,1,this.insertNode,[node.parentNode.parentNode]);//插入的节点为它的上一级目录
			return;
		}
		var dul = node&&node.lastChild;//取UL
		if(!(/text/i.test(cls))&&dul){//处理目录节点
			var dimg = null;
			for(var i=0;i<node.childNodes.length;i++){
				dimg = node.childNodes[i];
				cls = dimg.className;
				if(dimg.tagName=='IMG'&&(/(?:tvdash|tvicon)/i.test(cls))){
					var ncls = /open/i.test(cls)?cls.replace(/\-open/i,''):cls+'-open';
					dimg.className = ncls;
				}
			}
			dul.style.display = (dul.style.display!='block')?'block':'none';
			if(!dul.childNodes.length){
				var imgA = '<img class="tvdash-tl" src="'+this.iconpath+'" />';//虚线、开、关图标
				var imgB = '<img class="tvicon-tl" src="'+this.iconpath+'space.gif" />';//文件夹、文件图标
				dul.innerHTML = '<li class="text text-last" atid="0" pid="0" txt="getmore">'+imgA+imgB+'<a href="#"><img src="'+this.iconpath+'indicator_arrow.gif" /> 正在加载数据...</a></li>';
				this.getData(atid,pid,0,this.insertNode,[node]);
			}
			if(this.onNodeOpen&&this.onNodeOpen.constructor==Function){this.onNodeOpen(node);}//展开事件
		}
	},
	openUp:function(node){//向上展开节点
		var nodeparent = node&&node.parentNode;
		if(!nodeparent||nodeparent==this.treebox.firstChild){return;}
		if(nodeparent.style.display=='block'){return;}
		this.openNode(nodeparent.parentNode);
		this.openUp(nodeparent.parentNode);
	},
	preload:function(pldata){//预加载元素
		try{
			document.execCommand("BackgroundImageCache", false, true);
		}catch(e){}
		var imgPL = [];
		for(var i=0;i<pldata.length;i++){
			imgPL[i] = new Image();
			imgPL[i].src = pldata[i];
		}
	},
	resetLastChild:function(node){//重置目录节点最后子节点样式
		if(node&&node.lastChild){
			var dlast = node.lastChild.lastChild;
			dlast.className = dlast.className+'l';
			var dchild = dlast.childNodes,dimg = null;
			for(var i=0;i<dchild.length;i++){
				dimg = dchild[i];
				if(dimg.tagName=='IMG'){
					dimg.className = dimg.className.replace(/(tvdash\-f|tvdash\-t)(?!l)/i,'$1l');
				}
			}
		}
	},
	showEditMenu:function(left,top){//展开编辑菜单
                if (!this.editable)
                    return;
		var emenu = this.editmenu;
		emenu.style.left = left+'px';
		emenu.style.top = top+'px';
		emenu.style.visibility = 'visible';
		var node = this.selectedNode;
		var rootNode = (node.className=='root');
		if(rootNode && ! this.rootEditable){//根节点只允许添加按钮
			emenu.style.visibility = 'hidden';
		}else{
			emenu.innerHTML = emenu.data;
		}
	},
	setFocus:function(node){//设置当前选中节点
		var dlink = node.lastChild.previousSibling;
		if(!dlink||dlink.tagName!='A'){return;}
		dlink.className = 'selected';
		if(this.selectedNode&&this.selectedNode!=node){this.selectedNode.lastChild.previousSibling.className='';}
		this.selectedNode = node;
		if(this.onNodeFocus&&this.onNodeFocus.constructor==Function){this.onNodeFocus(node);}//聚焦事件
	},
	setOpenState:function(node,open){//设置节点展开状态
		if(!node||(/text/i.test(node.className))){return;}
		var dimg = null,cls = '';
		for(var i=0;i<node.childNodes.length;i++){
			dimg = node.childNodes[i];
			cls = dimg.className;
			if(dimg.tagName=='IMG'&&(/(?:tvdash|tvicon)/i.test(cls))){
				var ncls = (!open)?cls.replace(/\-open/i,''):cls+'-open';
				dimg.className = ncls;
			}
		}
		if(node.lastChild){node.lastChild.style.display = open?'block':'none';}
	},
	txtNode2Folder:function(node){//文本节点转目录节点
		var dchild = null,dimg = null,i=0;
		node.className = node.className.replace(/text/i,'folder');
		dchild = node.childNodes;dimg = null;
		for(var i=0;i<dchild.length;i++){
			dimg = dchild[i];
			if(dimg.tagName=='IMG'){
				dimg.className = dimg.className.replace(/(tvdash\-|tvicon\-)t(l?)$/i,'$1f$2');
			}
		}
	},
	treeNode:function(tv){//treenode construct
		this.onclick = function(e){
			e = e||window.event;var dtarg = e.srcElement||e.target,dtargTN = dtarg.tagName,dparent = dtarg.parentNode;
			switch(dtargTN){
				case 'IMG':
					var dtargCLS = dtarg.className;
					if(/tvdash/i.test(dtargCLS)){//开、关图标
						//展开节点
						tv.openNode(dparent);
					}
					if(/tvedit/i.test(dtargCLS)&&tv.editable){//编辑图标
						var pos = easyUI.getPosition(dtarg);
						var left = pos.x,top = pos.y+20;
						//设置选中
						tv.setFocus(dparent);
						//展开编辑菜单
						tv.showEditMenu(left,top);
					}
					break;
				case 'INPUT'://复选框
					if(tv.checkbox){
						var checked = dtarg.checked;
						if(checked&&tv.onNodeChecked&&tv.onNodeChecked.constructor==Function){tv.onNodeChecked(dparent);}//选中事件
						if(!checked&&tv.onNodeUnChecked&&tv.onNodeUnChecked.constructor==Function){tv.onNodeUnChecked(dparent);}//取消选中事件
						var chkbox = dparent.getElementsByTagName("Input");
						var cbl = chkbox.length;
						var dcparent = null;
						for(var i=1;i<cbl;i++){
							chkbox[i].checked = checked?true:false;
							dcparent = chkbox[i].parentNode;
							if(checked&&tv.onNodeChecked&&tv.onNodeChecked.constructor==Function){tv.onNodeChecked(dcparent);}//选中事件
							if(!checked&&tv.onNodeUnChecked&&tv.onNodeUnChecked.constructor==Function){tv.onNodeUnChecked(dcparent);}//取消选中事件
						}
						tv.checkUp(dparent);
					}
					break;
				case 'A'://文本内容
					easyUI.stopEvent(e);
					if(!(/正在加载数据/i.test(dtarg.innerHTML))){
						if(tv.onNodeClick&&tv.onNodeClick.constructor==Function){tv.onNodeClick(dparent);}//单击事件
						tv.setFocus(dparent);//设置选中
						tv.openNode(dparent,dtarg);//展开节点
					}
					break;
				default:break;
			}
		};
		this.ondblclick = function(e){//双击事件
			e = e||window.event;var dtarg = e.srcElement||e.target,dtargTN = dtarg.tagName,dparent = dtarg.parentNode;
			if(dtargTN=='A'){
				easyUI.stopEvent(e);
				if(!(/正在加载数据/i.test(dtarg.innerHTML))){
					if(tv.onNodeDblClick&&tv.onNodeDblClick.constructor==Function){tv.onNodeDblClick(dparent);}//双击事件
				}
			}
		};
		this.oncontextmenu = function(e){//右击事件
			e = e||window.event;var dtarg = e.srcElement||e.target,dtargTN = dtarg.tagName,dparent = dtarg.parentNode;
			if(dtargTN=='A'){
				easyUI.stopEvent(e);
				if(!(/正在加载数据/i.test(dtarg.innerHTML))){
					var pos = easyUI.getPosition(dtarg);
					var left = pos.x,top = pos.y+15;
					if(tv.onContextMenu&&tv.onContextMenu.constructor==Function){tv.setFocus(dparent);tv.onContextMenu(dparent,left,top);}//右击事件
				}
			}
		};
	},
	init:function(){//初始化
		this.preload([this.iconpath+"icon.png",this.iconpath+"i.gif",this.iconpath+"space.gif",this.iconpath+"indicator_arrow.gif"]);
		var chkStr = (this.checkbox)?'<input type="checkbox" />':'';
		var reditStr = '';//(this.editable)?'<img class="tvedit" src="'+this.iconpath+'space.gif" />':'';

		//var editStr = '';//(this.editable)?'<div class="editmenu"><ul><li><a class="tv-add" href="#">添加</a></li><li><a class="tv-edit" href="#">编辑</a></li><li><a class="tv-del" href="#">删除</a></li></ul></div>':'';
		var editStr = '<div class="editmenu"><ul>';
                for (var i = 0; i < this.editMenuContents.length; i++) {
                    editStr += '<li><a class="tv-edit" href="#">' + this.editMenuContents[i] + '</a></li>';
                }
                editStr += '</ul></div>';
                if (!this.editable)
                    editStr = '';
                this.treebox.innerHTML = '<ul class="dhatv4"><li class="root" atid="0" pid="0" txt="'+this.root+'"><img class="tvdash" src="'+this.iconpath+'space.gif" /><img class="tvicon" src="'+this.iconpath+'space.gif" />'+chkStr+reditStr+'<a href="#">'+this.root+'</a><ul></ul></li></ul>'+editStr;
		this.treeNode.call(this.treebox.childNodes[0],this);
		if(this.editable){//是否允许编辑
			this.editmenu = this.treebox.childNodes[1];
			this.editmenu.style.position = 'absolute';
			this.editmenu.style.zIndex = 100;
			this.editmenu.style.left = 0;
			this.editmenu.style.top = 0;
			this.editmenu.style.visibility = 'hidden';
			this.editmenu.data = this.editmenu.innerHTML;
			this.editmenu.onclick = this.editEvent.bind(this);
			if(document.attachEvent){
				document.attachEvent("onmousedown",function(o){return function(e){e=e||window.event;var et=e.srcElement||e.target;if(!o.contains(et)){o.style.visibility='hidden';}};}(this.editmenu));
			}else{
				document.addEventListener("mousedown",function(o){return function(e){e=e||window.event;var et=e.srcElement||e.target;if((o.contains&&!o.contains(et))||(o.compareDocumentPosition&&o.compareDocumentPosition(et)!=20)){o.style.visibility='hidden';}};}(this.editmenu),false);
			}
			window.onunload = function(){document.onmousedown = function(){};};
		}
	}
};

/**
 * 创建一颗简单的树，只有简单的显示功能
 * @param ele
 * @param treeName
 * @param data
 * @return
 */
function createSimpleTree(ele, treeName, data) {
    var thistree = new Dhatv(document.getElementById(ele));;
    thistree.root = treeName;
    thistree.rootEditable = false;
    if (data.constructor==Array) {
        thistree.datasource = data;
    } else {
        thistree.dataurl = data;
    }
    thistree.checkbox = false;
    thistree.iconpath = contextPath + "resources/easyUI/";
    //如果扩展属性没有则使用空数组
    thistree.extpp = [];
    thistree.sortable = 'asc';
    thistree.sortIndex = 1;
    thistree.editMenuContents = [];
    thistree.editMenuFunction = [];
    thistree.editable = false;
    thistree.onNodeOpen = null;
    thistree.onNodeFocus = null;
    //当复选框启用的时候，如果被选中则触发此事件
    thistree.onNodeChecked = null;
    //当复选框启用的时候，如果取消选中则触发此事件
    thistree.onNodeUnChecked = null;
    //单击节点时触发的事件函数
    thistree.onNodeClick = null;
    //双击鼠标左键时弹出编辑当前节点界面
    thistree.onNodeDblClick = null;
    //单击鼠标右键时出现的菜单
    thistree.onContextMenu = null;
    return thistree;
}

/*
 * 选择树对象
 * ele：必须传入此树渲染到那个标签中，一般为div
 * treeName：必须给树取个名字
 * data：树的数据来源,如果是数组则使用数组，如果是字符串则当成是由ajax异步传输过来的内容
 * retObjs：返回的对象
 * retProp：返回的属性
 * multiSelect：是否多选，默认为单选
 * targetDom：目标文档对象，默认为当前文档对象，即弹出式对话框
 */
var SelectTree = function(ele, treeName, data, extpp, retObjs, retProp, multiSelect) {
    var tree = createSimpleTree(ele, treeName, data);
    if (extpp && extpp.constructor == Array) {
    	tree.extpp = extpp;
    }
    tree.checkbox = multiSelect?multiSelect:false;
    if (multiSelect) {//表示此树是可以多选的
    	//...
    } else { //单选树
    	tree.onNodeClick = function(node) {
    		if (retObjs && retObjs.constructor == Array
    				&& retProp && retProp.constructor == Array) {
    			for (var i = 0; i < retObjs.length; i++) {
    				document.getElementById(retObjs[i]).value = node[retProp[i]];
    			}
    		}
    		document.getElementById(ele).innerHTML = '';
    	}
    }
    this.render = function() {
        tree.init();
        tree.focusNode([0,0]);
    }
    this.tree = tree;
}

var MenuTree = function(ele, treeName, data,extpp, clickFunction) {
	var tree = createSimpleTree(ele, treeName, data);
	if (extpp)
		tree.extpp = extpp;
	if (clickFunction && clickFunction.constructor == Function)
		tree.onNodeClick = clickFunction;
	this.render = function() {
		tree.init();
		tree.focusNode([0,0]);
	}
	this.tree = tree;
}

var EditableTree = function(ele, treeName, data, extpp, menuContent, menuFunctions) {
	var tree = createSimpleTree(ele, treeName, data);
	if (extpp)
		tree.extpp = extpp;
	if (menuContent && menuContent.length > 0 && menuFunctions && menuFunctions.length > 0) {
		tree.editMenuContents = menuContent;
		tree.editMenuFunction = menuFunctions;
		tree.editable = true;
		tree.onContextMenu = function(node,x,y){tree.showEditMenu(x,y);};
	}
	this.render = function() {
		tree.init();
		tree.focusNode([0,0]);
	}
	this.tree = tree;
}

var contextPath = '/cang/';